#!/usr/bin/env python3
"""
用户服务测试脚本
测试用户服务的基本功能和API端点
"""
import requests
import json
import time
from typing import Dict, Any

class UserServiceTester:
    def __init__(self, base_url: str = "http://localhost:8003"):
        self.base_url = base_url
        self.session = requests.Session()
        self.test_user_data = {
            "username": "testuser123",
            "email": "test@example.com",
            "password": "TestPassword123!",
            "full_name": "Test User"
        }
    
    def wait_for_service(self, timeout: int = 30) -> bool:
        """等待服务启动"""
        print("等待用户服务启动...")
        start_time = time.time()
        
        while time.time() - start_time < timeout:
            try:
                response = self.session.get(f"{self.base_url}/health")
                if response.status_code == 200:
                    print("✅ 用户服务已启动")
                    return True
            except requests.exceptions.RequestException:
                pass
            time.sleep(1)
        
        print("❌ 服务启动超时")
        return False
    
    def test_health_check(self) -> bool:
        """测试健康检查端点"""
        print("\n📋 测试健康检查...")
        try:
            response = self.session.get(f"{self.base_url}/health")
            if response.status_code == 200:
                data = response.json()
                print(f"✅ 健康检查成功: {data}")
                return True
            else:
                print(f"❌ 健康检查失败: {response.status_code}")
                return False
        except Exception as e:
            print(f"❌ 健康检查异常: {e}")
            return False
    
    def test_user_registration(self) -> Dict[str, Any]:
        """测试用户注册"""
        print("\n👤 测试用户注册...")
        try:
            response = self.session.post(
                f"{self.base_url}/api/v1/users/register",
                json=self.test_user_data
            )
            
            if response.status_code == 201:
                data = response.json()
                print(f"✅ 用户注册成功: {data.get('username')}")
                return data
            else:
                print(f"❌ 用户注册失败: {response.status_code} - {response.text}")
                return {}
        except Exception as e:
            print(f"❌ 用户注册异常: {e}")
            return {}
    
    def test_user_login(self) -> str:
        """测试用户登录"""
        print("\n🔐 测试用户登录...")
        try:
            login_data = {
                "username": self.test_user_data["username"],
                "password": self.test_user_data["password"]
            }
            
            response = self.session.post(
                f"{self.base_url}/api/v1/auth/login",
                data=login_data
            )
            
            if response.status_code == 200:
                data = response.json()
                token = data.get("access_token")
                print(f"✅ 用户登录成功")
                return token
            else:
                print(f"❌ 用户登录失败: {response.status_code} - {response.text}")
                return ""
        except Exception as e:
            print(f"❌ 用户登录异常: {e}")
            return ""
    
    def test_user_profile(self, token: str) -> bool:
        """测试获取用户资料"""
        print("\n👤 测试获取用户资料...")
        try:
            headers = {"Authorization": f"Bearer {token}"}
            response = self.session.get(
                f"{self.base_url}/api/v1/users/me",
                headers=headers
            )
            
            if response.status_code == 200:
                data = response.json()
                print(f"✅ 获取用户资料成功: {data.get('username')}")
                return True
            else:
                print(f"❌ 获取用户资料失败: {response.status_code}")
                return False
        except Exception as e:
            print(f"❌ 获取用户资料异常: {e}")
            return False
    
    def test_api_docs(self) -> bool:
        """测试API文档端点"""
        print("\n📚 测试API文档...")
        try:
            response = self.session.get(f"{self.base_url}/docs")
            if response.status_code == 200:
                print("✅ API文档可访问")
                return True
            else:
                print(f"❌ API文档访问失败: {response.status_code}")
                return False
        except Exception as e:
            print(f"❌ API文档访问异常: {e}")
            return False
    
    def cleanup_test_user(self, token: str) -> bool:
        """清理测试用户（如果有删除接口）"""
        print("\n🧹 清理测试数据...")
        try:
            headers = {"Authorization": f"Bearer {token}"}
            response = self.session.delete(
                f"{self.base_url}/api/v1/users/me",
                headers=headers
            )
            
            if response.status_code in [200, 204]:
                print("✅ 测试用户清理成功")
                return True
            else:
                print(f"⚠️ 测试用户清理失败: {response.status_code}")
                return False
        except Exception as e:
            print(f"⚠️ 测试用户清理异常: {e}")
            return False
    
    def run_all_tests(self):
        """运行所有测试"""
        print("🚀 开始用户服务测试...")
        
        # 等待服务启动
        if not self.wait_for_service():
            print("❌ 服务未启动，退出测试")
            return
        
        # 测试计数
        total_tests = 0
        passed_tests = 0
        
        # 健康检查
        total_tests += 1
        if self.test_health_check():
            passed_tests += 1
        
        # API文档
        total_tests += 1
        if self.test_api_docs():
            passed_tests += 1
        
        # 用户注册
        total_tests += 1
        user_data = self.test_user_registration()
        if user_data:
            passed_tests += 1
        
        # 用户登录
        token = ""
        if user_data:
            total_tests += 1
            token = self.test_user_login()
            if token:
                passed_tests += 1
        
        # 用户资料
        if token:
            total_tests += 1
            if self.test_user_profile(token):
                passed_tests += 1
        
        # 清理测试数据
        if token:
            self.cleanup_test_user(token)
        
        # 测试结果
        print(f"\n📊 测试结果: {passed_tests}/{total_tests} 通过")
        if passed_tests == total_tests:
            print("🎉 所有测试通过！")
        else:
            print("⚠️ 部分测试失败")

if __name__ == "__main__":
    tester = UserServiceTester()
    tester.run_all_tests()
